/*
 * Copyright (C) 2008 The Android Open Source Project
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef _LINKER_H_
#define _LINKER_H_

#include <unistd.h>
#include <sys/types.h> 
#include <elf.h>
#include <sys/exec_elf.h>

// NACL MOD BEGIN
// We usually define macros like ElfW(type) so ElfW(Ehdr) can be
// either Elf32_Ehdr or Elf64_Ehdr. However, we map all Elf32_* types
// to Elf64_* types to minimize the number of NACL MOD.
#if defined(ANDROID_X86_64_LINKER)
#define Elf32_Addr Elf64_Addr
#define Elf32_Ehdr Elf64_Ehdr
#define Elf32_Half Elf64_Half
#define Elf32_Phdr Elf64_Phdr
#define Elf32_Sym Elf64_Sym
#endif

// NACL MOD END
// NACL MOD BEGIN UPSTREAM
// linker.cpp does not have as many following macros as the above
// structure types. We can make the ideal change for them.
#if defined(ANDROID_X86_64_LINKER)
#define ELFW(x) ELF64_ ## x
#else
#define ELFW(x) ELF32_ ## x
#endif

// NACL MOD END UPSTREAM
#ifdef __cplusplus
extern "C" {
#endif
#include <link.h>

#undef PAGE_MASK
#undef PAGE_SIZE
/* NACL MOD BEGIN UPSTREAM */
/* Page size on NaCl is 0x10000 */
#if defined(__native_client__)
#define PAGE_SIZE 0x10000
#else
#define PAGE_SIZE 4096
#endif
/* NACL MOD END UPSTREAM */
#define PAGE_MASK (PAGE_SIZE-1)

/* Convenience macros to make page address/offset computations more explicit */

/* Returns the address of the page starting at address 'x' */
#define PAGE_START(x)  ((x) & ~PAGE_MASK)

/* Returns the offset of address 'x' in its memory page, i.e. this is the
 * same than 'x' - PAGE_START(x) */
#define PAGE_OFFSET(x) ((x) & PAGE_MASK)

/* Returns the address of the next page after address 'x', unless 'x' is
 * itself at the start of a page. Equivalent to:
 *
 *  (x == PAGE_START(x)) ? x : PAGE_START(x)+PAGE_SIZE
 */
#define PAGE_END(x)    PAGE_START((x) + (PAGE_SIZE-1))

void debugger_init();

/* magic shared structures that GDB knows about */

struct link_map
{
    // NACL MOD BEGIN
    // GDB expects this to be a 64 bit integer on x86-64 NaCl.
    // See third_party/nacl-glibc/elf/link.h.
#if defined(ANDROID_X86_64_LINKER) && defined(__native_client__)
    Elf64_Addr l_addr;
#else
    uintptr_t l_addr;
#endif
    // NACL MOD END
    char * l_name;
    uintptr_t l_ld;
    struct link_map * l_next;
    struct link_map * l_prev;
};

// Values for r_debug->state
enum {
    RT_CONSISTENT,
    RT_ADD,
    RT_DELETE
};

struct r_debug
{
    int32_t r_version;
    struct link_map * r_map;
    // NACL MOD BEGIN
    // GDB expects r_brk and r_ldbase to be 64 bit values on x86-64 NaCl.
    // See third_party/nacl-glibc/elf/link.h.
#if defined(ANDROID_X86_64_LINKER) && defined(__native_client__)
    void (*r_brk)(void);
    uintptr_t r_brk_zero;
    int32_t r_state;
    uintptr_t r_ldbase;
    uintptr_t r_ldbase_zero;
#else
    // NACL MOD END
    void (*r_brk)(void);
    int32_t r_state;
    uintptr_t r_ldbase;
    // NACL MOD BEGIN
#endif
    // NACL MOD END
};

typedef struct soinfo soinfo;

#define FLAG_LINKED     0x00000001
#define FLAG_ERROR      0x00000002
#define FLAG_EXE        0x00000004 // The main executable
#define FLAG_LINKER     0x00000010 // The linker itself

#define SOINFO_NAME_LEN 128

struct soinfo
{
    char name[SOINFO_NAME_LEN];
    const Elf32_Phdr *phdr;
    int phnum;
    unsigned entry;
    unsigned base;
    // NACL MOD BEGIN
    // There are no code change, but the meaning of this field has
    // changed. In the original Bionic, this field contains the total
    // size loaded segments and it assumes there are no gaps between
    // each segment. For NaCl, we use this field as the size of the
    // text segment. NaCl binary has a big gap between the text
    // segment and the data segments so if we use the original value,
    // find_containing_library will not return the correct library.
    // NACL MOD END
    unsigned size;

    int unused;  // DO NOT USE, maintained for compatibility.

    // NACL MOD BEGIN
    // This pointer points at Elf32_Dyn or Elf64_Dyn. Elf32_Dyn has
    // two 32bit integers and Elf64_Dyn has two 64bit integers.
    // We will iterate dynamic segment by for loops like
    //
    // for (d = dynamic; *d; d += 2)
    //
    // So, we need to use a 64bit integer type for this field. We use
    // Elf32_Addr instead of unsigned for this purpose. Note that we
    // are mapping Elf32_Addr to Elf64_Addr for x86-64.
    Elf32_Addr *dynamic;
    // NACL MOD END

    unsigned unused2; // DO NOT USE, maintained for compatibility
    unsigned unused3; // DO NOT USE, maintained for compatibility

    // Libraries are stored as a flattened search order.  Depth is used
    // to allow new (or old) libraries pulled in via DT_NEEDED to find
    // the correct place in the search list.
    int depth;
    soinfo *next;
 
    unsigned flags;

    const char *strtab;
    Elf32_Sym *symtab;

    unsigned nbucket;
    unsigned nchain;
    unsigned *bucket;
    unsigned *chain;

    unsigned *plt_got;

    // NACL MOD BEGIN
    // System V Application Binary Interface AMD64 Architecture
    // Processor Supplement says "The AMD64 ABI architectures uses
    // only Elf64_Rela relocation entries with explicit addends."
    // http://www.x86-64.org/documentation/abi.pdf
#if defined(ANDROID_X86_64_LINKER)
    Elf64_Rela *plt_rel;
#else
    Elf32_Rel *plt_rel;
#endif
    // NACL MOD END
    unsigned plt_rel_count;

    // NACL MOD BEGIN
    // AMD64 ABI says we should always use Elf64_Rela for x86-64.
#if defined(ANDROID_X86_64_LINKER)
    Elf64_Rela *rel;
#else
    Elf32_Rel *rel;
#endif
    // NACL MOD END
    unsigned rel_count;

    unsigned *preinit_array;
    unsigned preinit_array_count;

    unsigned *init_array;
    unsigned init_array_count;
    unsigned *fini_array;
    unsigned fini_array_count;

    void (*init_func)(void);
    void (*fini_func)(void);

#if defined(ANDROID_ARM_LINKER)
    /* ARM EABI section used for stack unwinding. */
    unsigned *ARM_exidx;
    unsigned ARM_exidx_count;
#elif defined(ANDROID_MIPS_LINKER)
#if 0
     /* not yet */
     unsigned *mips_pltgot
#endif
     unsigned mips_symtabno;
     unsigned mips_local_gotno;
     unsigned mips_gotsym;
#endif /* ANDROID_*_LINKER */

    unsigned refcount;
    struct link_map linkmap;

    int constructors_called;

    /* When you read a virtual address from the ELF file, add this
     * value to get the corresponding address in the process' address space */
    Elf32_Addr load_bias;
    int has_text_relocations;
};


extern soinfo libdl_info;


#include <asm/elf.h>

#if defined(ANDROID_ARM_LINKER)

// These aren't defined in <arch-arm/asm/elf.h>.
#define R_ARM_REL32      3
#define R_ARM_COPY       20
#define R_ARM_GLOB_DAT   21
#define R_ARM_JUMP_SLOT  22
#define R_ARM_RELATIVE   23

#elif defined(ANDROID_MIPS_LINKER)

// These aren't defined in <arch-arm/mips/elf.h>.
#define R_MIPS_JUMP_SLOT       127

#define DT_MIPS_PLTGOT         0x70000032
#define DT_MIPS_RWPLT          0x70000034

#elif defined(ANDROID_X86_LINKER)

// x86 has everything it needs in <arch-arm/x86/elf.h>.
// NACL MOD BEGIN

// Add x86-64 relocations types. Copied from
// http://svnweb.freebsd.org/base/head/sys/sys/elf_common.h?revision=249558
#elif defined(ANDROID_X86_64_LINKER)

#define R_X86_64_NONE           0       /* No relocation. */
#define R_X86_64_64             1       /* Add 64 bit symbol value. */
#define R_X86_64_PC32           2       /* PC-relative 32 bit signed sym value. */
#define R_X86_64_GOT32          3       /* PC-relative 32 bit GOT offset. */
#define R_X86_64_PLT32          4       /* PC-relative 32 bit PLT offset. */
#define R_X86_64_COPY           5       /* Copy data from shared object. */
#define R_X86_64_GLOB_DAT       6       /* Set GOT entry to data address. */
#define R_X86_64_JMP_SLOT       7       /* Set GOT entry to code address. */
#define R_X86_64_RELATIVE       8       /* Add load address of shared object. */
#define R_X86_64_GOTPCREL       9       /* Add 32 bit signed pcrel offset to GOT. */
#define R_X86_64_32             10      /* Add 32 bit zero extended symbol value */
#define R_X86_64_32S            11      /* Add 32 bit sign extended symbol value */
#define R_X86_64_16             12      /* Add 16 bit zero extended symbol value */
#define R_X86_64_PC16           13      /* Add 16 bit signed extended pc relative symbol value */
#define R_X86_64_8              14      /* Add 8 bit zero extended symbol value */
#define R_X86_64_PC8            15      /* Add 8 bit signed extended pc relative symbol value */
#define R_X86_64_DTPMOD64       16      /* ID of module containing symbol */
#define R_X86_64_DTPOFF64       17      /* Offset in TLS block */
#define R_X86_64_TPOFF64        18      /* Offset in static TLS block */
#define R_X86_64_TLSGD          19      /* PC relative offset to GD GOT entry */
#define R_X86_64_TLSLD          20      /* PC relative offset to LD GOT entry */
#define R_X86_64_DTPOFF32       21      /* Offset in TLS block */
#define R_X86_64_GOTTPOFF       22      /* PC relative offset to IE GOT entry */
#define R_X86_64_TPOFF32        23      /* Offset in static TLS block */
#define R_X86_64_IRELATIVE      37
// NACL MOD END

#endif /* ANDROID_*_LINKER */

#ifndef DT_INIT_ARRAY
#define DT_INIT_ARRAY      25
#endif

#ifndef DT_FINI_ARRAY
#define DT_FINI_ARRAY      26
#endif

#ifndef DT_INIT_ARRAYSZ
#define DT_INIT_ARRAYSZ    27
#endif

#ifndef DT_FINI_ARRAYSZ
#define DT_FINI_ARRAYSZ    28
#endif

#ifndef DT_PREINIT_ARRAY
#define DT_PREINIT_ARRAY   32
#endif

#ifndef DT_PREINIT_ARRAYSZ
#define DT_PREINIT_ARRAYSZ 33
#endif


soinfo *find_loaded_library(const char *name);
soinfo *load_library(const char *name, int depth);
int soinfo_link_image(soinfo* si);

Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start);
soinfo *find_containing_library(const void *addr);
const char *linker_get_error(void);

int soinfo_unload(soinfo* si);
Elf32_Sym *soinfo_find_symbol(soinfo* si, const void *addr);
Elf32_Sym *soinfo_lookup(soinfo *si, const char *name);
void soinfo_call_constructors(soinfo *si);

#ifdef __cplusplus
};
#endif

#endif
